<?php

declare(strict_types=1);

namespace app\common\model;
use addons\Sms\facade\Sms;
class Code extends Base
{
    protected $name = 'user_code';
    /**
     * 短信
     */
    public static function sendSmsCode($param):array
    {
        try {
            $time= time();
            $smscode = parent::where(['mobile' => $param['mobile'], 'status' => 0,'type'=>$param['action']])->where('end_time', '>', $time)->find();       
            if (empty($smscode)) {
                $code = generate(6, '', 1);
                $data['create_time'] = $time;
                $data['end_time'] = $time + 600;
                $data['mobile'] = $param['mobile'];
                $data['code'] = $code;
                $data['type'] = $param['action'];
                $data['action'] = 'sendSms';
                $res = Sms::send($param['mobile'], '您的验证码是：' . $code . '。十分钟之内有效，请勿告诉他人');
                if ($res['code'] == 200) {
                    parent::create($data);
                    $msg = '发送成功！';
                    $codes = 1;
                } else {
                    $msg = '发送失败！';
                    $codes = -1;
                }
            } else {
                $code = intval($smscode['code']);
                $msg = '发送成功！';
                $codes = 1;
            }
            return ['code' => $codes, 'msg' => $msg,'data'=>$code];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
